package com.cqggrw.util;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;

public class Utils {
	private static Logger log = Logger.getLogger(Utils.class);
	private static int wh = 120;
	private static int hi = 30;
	public static String yanzheng = "";
	public static String separator = java.io.File.separator;
	public static boolean closeApp = false;

	public static void writeJson(Object object) {
		try {
			String json = JSON.toJSONStringWithDateFormat(object,
					"yyyy-MM-dd HH:mm:ss", new SerializerFeature[0]);
			ServletActionContext.getResponse().setContentType(
					"text/html;charset=utf-8");
			ServletActionContext.getResponse().getWriter().write(json);
			ServletActionContext.getResponse().getWriter().flush();
			ServletActionContext.getResponse().getWriter().close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static boolean upFile(String fileName, String savePath, File file)
			throws IOException {
		boolean falg = false;
		if (file != null) {
			File saveFile = new File(new File(savePath), fileName);
			if (!saveFile.getParentFile().exists()) {
				saveFile.getParentFile().mkdirs();
			}
			FileUtils.copyFile(file, saveFile);
			falg = true;
		}
		return falg;
	}

	public static void log(Exception e) {
		String clazz = e.getClass().toString();
		String localizedMessage = e.getLocalizedMessage();
		log.info(clazz + "  " + localizedMessage);
		for (StackTraceElement stl : e.getStackTrace()) {
			String className = stl.getClassName();
			String methodName = stl.getMethodName();
			String fileName = stl.getFileName();
			int lineNumber = stl.getLineNumber();
			log.info("    " + className + "." + methodName + "(" + fileName
					+ ":" + lineNumber + ")");
		}

	}

	public static void log(String info) {
		log.info(info);
	}

	public static Map<String, Object> getImg() {
		Map<String, Object> map = new HashMap<String, Object>();

		BufferedImage buimg = new BufferedImage(wh, hi,
				BufferedImage.TYPE_INT_RGB);
		Graphics g = buimg.getGraphics();

		g.setColor(Color.WHITE);

		g.fillRect(0, 0, wh - 2, hi - 2);

		shuijixian(g);

		zhi((Graphics2D) g);

		map.put("imgIo", buimg);
		map.put("code", yanzheng);

		return map;
	}

	private static void zhi(Graphics2D g) {
		g.setColor(Color.red);
		g.setFont(new Font("Default", Font.BOLD, 20));

		String s = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLMNBVCXZ0123456789";
		int x = 10;
		yanzheng = "";
		for (int i = 0; i < 4; i++) {
			int xuan = new Random().nextInt() % 50;//
			int len = new Random().nextInt(s.length() - 1);
			String s1 = s.substring(len, len + 1);
			yanzheng += s1;
			g.rotate(xuan * Math.PI / 180, x, 20);
			g.drawString(s1, x, 20);
			g.rotate(-xuan * Math.PI / 180, x, 20);
			x += 30;
		}
	}

	private static void shuijixian(Graphics g) {
		g.setColor(Color.GREEN);
		for (int i = 0; i < 5; i++) {
			int x1 = new Random().nextInt(wh);
			int y1 = new Random().nextInt(hi);

			int x2 = new Random().nextInt(wh);
			int y2 = new Random().nextInt(hi);
			g.drawLine(x1, y1, x2, y2);
		}
	}

	public static boolean unzip(File zipFile, String outputDirectory) {
		boolean flag = true;
		File file = new File(outputDirectory);
		file.mkdirs();
		file = null;
		ZipInputStream in = null;
		try {
			in = new ZipInputStream(new FileInputStream(zipFile));
			ZipEntry z;
			while ((z = in.getNextEntry()) != null) {
				Utils.log("unziping " + z.getName());
				if (z.isDirectory()) {
					String name = z.getName();
					name = name.substring(0, name.length() - 1);
					File f = new File(outputDirectory + File.separator + name);
					f.mkdir();
					Utils.log("mkdir " + outputDirectory + File.separator
							+ name);
				} else {
					File f = new File(outputDirectory + File.separator
							+ z.getName());
					f.createNewFile();
					FileOutputStream out = new FileOutputStream(f);
					int b;
					while ((b = in.read()) != -1)
						out.write(b);
					out.close();
				}
			}
			in.close();
		} catch (Exception e) {
			flag = false;
			Utils.log(e);
		}
		return flag;
	}

	public static void deleteDir(File dir) {
		if (dir == null || !dir.exists() || !dir.isDirectory())
			return; // 检查参数
		for (File file : dir.listFiles()) {
			if (file.isFile())
				file.delete(); // 删除所有文件
			else if (file.isDirectory())
				deleteDir(file); // 递规的方式删除文件夹
		}
		dir.delete();// 删除目录本身
	}
	
	/** 
     * 给定根目录，返回另一个文件名的相对路径，用于zip文件中的路径. 
     *  
     * @param baseDir 
     *            java.lang.String 根目录 
     * @param realFileName 
     *            java.io.File 实际的文件名 
     * @return 相对文件名 
     */  
    private static String getAbsFileName(String baseDir, File realFileName) {  
        File real = realFileName;  
        File base = new File(baseDir);  
        String ret = real.getName();  
        while (true) {  
            real = real.getParentFile();  
            if (real == null)  
                break;  
            if (real.equals(base))  
                break;  
            else  
                ret = real.getName() + "/" + ret;  
        }  
        return ret;  
    }  
  
    /** 
     * 取得指定目录下的所有文件列表，包括子目录. 
     *  
     * @param baseDir 
     *            File 指定的目录 
     * @return 包含java.io.File的List 
     */  
    private static List<File> getSubFiles(File baseDir) {  
        List<File> ret = new ArrayList<File>();  
        File[] tmp = baseDir.listFiles();  
        for (int i = 0; i < tmp.length; i++) {  
            if (tmp[i].isFile()){  
                ret.add(tmp[i]);  
            }  
            if (tmp[i].isDirectory()){  
                ret.addAll(getSubFiles(tmp[i]));  
            }  
        }  
        return ret;  
    } 
	
	public static void zipFile(String baseDir, ZipOutputStream zos)throws Exception {  
        List<File> fileList = getSubFiles(new File(baseDir));  
        ZipEntry ze = null;  
        byte[] buf = new byte[1024];  
        int readLen = 0;  
        for (int i = 0; i < fileList.size(); i++) {  
            File f = (File) fileList.get(i);  
            ze = new ZipEntry(getAbsFileName(baseDir, f));  
            ze.setSize(f.length());  
            ze.setTime(f.lastModified());  
            zos.putNextEntry(ze);  
            InputStream is = new BufferedInputStream(new FileInputStream(f));  
            while ((readLen = is.read(buf, 0, 1024)) != -1) {  
                zos.write(buf, 0, readLen);  
            }  
            is.close();  
        }  
        zos.closeEntry();  
        zos.close();  
    } 
}
